<?php
/**
 * This file is part of the Agora distribution. 
 * Detailed copyright and licensing information can be found
 * in the gpl-3.0.txt file which should be included in the distribution.
 * 
 * @version		$Id: 3.0.14 Olympus 2010-09-28 rammstein4o $
 * @copyright  2007 - 2010 jVitals
 * @license   GPLv3 Open Source
 * @link       http://jvitals.com
 * @since      File available since initial release
 */
defined ('IN_AGORA') or die;

class TaskController extends AgoraController {

    function __construct() {
        parent::__construct();
        
        $mode = Agora::getVar('mode');
        if (strpos($_SERVER['PHP_SELF'],'index2.php') != 0) $mode='agroup';
        
        if ('agroup' == $mode) {
			$this->loadDefaultView( null, 'view_agroup');
        } else {
			$this->loadDefaultView();
		}
    }

    // extract parent forums and categories path from common forumList array and publish it to template
    function _buildPathWay($forum, $topic, $mode=false) {
        $forum_id = $forum['id'];
        $cat_id = $forum['cat_id'];
        $category = $this->forumList[$cat_id];

        $pathway = & $this->helper('pathway');

        while ($forum_id != 0) {
            $forum = $category['forums'][$forum_id];
            if ('agroup'==$mode)
            $pathway->push($forum['forum_name'],Agora::makeURL(array('task' => 'forum', 'id' => $forum['id']), true, true));
            else
            $pathway->push($forum['forum_name'],Agora::makeURL(array('task' => 'forum', 'id' => $forum['id'])));
            
            $forum_id = $forum['parent_forum_id'];
        };

        // prepend with category
        if ('agroup'==$mode)
        $pathway->push($category['cat_name'],Agora::makeURL(array('id' => $cat_id), true, true));
        else
        $pathway->push($category['cat_name'],Agora::makeURL(array('id' => $cat_id)));
        
        // append topic subject without link - user already has link in his browser
        $pathway->add($topic['subject'],'');
    }

    function _processPoll($topic) {
        $poll_model = & Model::getInstance('PollModel');
        $poll = $poll_model->load($topic['id'],'pollid');
		
		$access_helper = & $this->helper('access');
		$access = $access_helper->getForumAccess($topic['forum_id']);
        

        if ($poll) {

            if (is_array($poll['voters']) && in_array($this->agora_user['id'],$poll['voters'])) {
                $poll['voted'] = true;
            } else {
                $poll['voted'] = false;
            }
			// this is wrong - guests must vote if they have the corresponding right
			/*
            if ($this->agora_user['is_guest']) {
                $poll['voted'] = true;
            }
			*/

            if ($poll['ptype'] == 1) {
                $poll['type'] = 'regular';
            } elseif ($poll['ptype'] == 2) {
                $poll['type'] = 'multi';
            } elseif ($poll['ptype'] == 3) {
                $poll['type'] = 'multi_yes_no';
            }

            if (!is_array($poll['votes'])) $poll['votes'] = array();
            if (!is_array($poll['options'])) $poll['options'] = array();

            $total = 0;

            foreach ($poll['votes'] as $votes) {
                if ($poll['ptype'] == '3') {
                    foreach ($votes as $option) {
                        $total += $option;
                    }
                } else {
                    $total += $votes;
                }
            }

            $poll['total_votes'] = $total;

/*			if ($poll['ptype'] == '3') {
                $total /= count($poll['options']);
            }*/

            if ($poll['voted'] || !$access['post_reply']) {
                $option = null;
                foreach ($poll['options'] as $key=>$option) {
                    $poll['options'][$key] = array('name' => $option);

                    $vote = & $poll['votes'][$key];

                    if (isset($poll['votes'][$key]) && $total > 0) {
                        if ($poll['ptype'] != '3') {
                            $poll['options'][$key]['percent'] = floor($vote * 100 / $total);
                            $poll['options'][$key]['count'] = $vote;
                        } else {
                            if (!isset($vote['yes'])) $vote['yes'] = 0;
                            if (!isset($vote['no'])) $vote['no'] = 0;
                            $poll['options'][$key]['yes_percent'] = floor($vote['yes'] * 100 / $total);
                            $poll['options'][$key]['yes_count'] = $vote['yes'];
                            $poll['options'][$key]['no_percent'] = floor($vote['no'] * 100 / $total);
                            $poll['options'][$key]['no_count'] = $vote['no'];
                        }
                    } else {
                        if ($poll['ptype'] != '3') {
                            $poll['options'][$key]['percent'] = 0;
                            $poll['options'][$key]['count'] = 0;
                        } else {
                            $poll['options'][$key]['yes_percent'] = 0;
                            $poll['options'][$key]['yes_count'] = 0;
                            $poll['options'][$key]['no_percent'] = 0;
                            $poll['options'][$key]['no_count'] = 0;
                        }
                    }
                }
            }

            $this->view->assign('poll',$poll);
        }
    }

    // the same as for forum for now
    function _setHeadTags($forum, $topic, $pagenum = false) {
        $document = & JFactory::getDocument();
        $document->setTitle($topic['subject'] . ' :: ' . $forum['forum_name'] . (empty($pagenum) ? '' : ' :: ' . Agora::lang('PAGEX', intval($pagenum))));
        $document->setMetaData ('keywords', $forum['forum_key']);
        $document->setDescription($forum['forum_mdesc']);
    }

    function _default() {
        $topic_id = (int)Agora::getVar('id');
        $mode = Agora::getVar('mode');                        
        if ( strpos($_SERVER['PHP_SELF'],'index2.php')!=0 ) $mode='agroup';
        
        $topic_model = & Model::getInstance('TopicModel');
        $topic = $topic_model->load($topic_id);

        $this->authenticate($topic['forum_id'],'read');

        $topic['subscribed'] = $topic_model->isSubscribed($topic_id, $this->agora_user['id']);

        if (empty($topic) || !is_array($topic) || !array_key_exists('forum_id', $topic)) {
            Agora::show404();
            return;
        }
        
		/*
		if (!$this->agora_user['is_guest'])
        {
            setcookie("agora_topic[$topic_id][num_replies]", $topic["num_replies"]);
        }
		*/        
        $topic_model->addView($topic_id, $this->agora_user['id']);
        $message = Agora::getSessionVar('message');
        Agora::setSessionVar('message', '');

        // load forum
        $forum_id = (int) $topic['forum_id'];
        $forum_model = & Model::getInstance('ForumModel');
        $forum = $forum_model->load($forum_id);

        $catnav_helper = & $this->helper('catnav');
        $catnav_helper->fromCategory($forum['cat_id']);

        $this->_buildPathWay($forum, $topic, $mode);

        // get access parameters for forum
		$access_helper = & $this->helper('access');
		$access = $access_helper->getForumAccess($forum_id);
		
        if ($this->agora_user['is_guest']) {
            $banned = false;
        } else {
            $ban_model = & Model::getInstance('BanModel');
            $banned = $ban_model->isBanned($this->agora_user['username']);
        }
        
        if ($banned) {
            $access['post_topic'] = false;
            $access['post_poll'] = false;
            $access['post_reply'] = false;
            $access['can_moderate'] = false;
        }
		
		if ($access['close_topic'] && (($this->agora_user['is_superadmin'] || $access['can_moderate']) || ($this->agora_user['username'] == $topic['poster'])) ) {
			$access['close_topic'] = true;
		} else {
			$access['close_topic'] = false;
		}
		
        if ($this->agora_user['is_superadmin'] || $access['can_moderate']) {
            $plugin       =& JPluginHelper::getPlugin('agora', 'agoraautoarticle');
			$plugin_params = (is_object($plugin) && property_exists($plugin, 'params')) ? $plugin->params : null;
	        $pluginParams = new JParameter( $plugin_params );
	        
	        if (!$pluginParams->get( 'plg_mode', '' ))
            if ($pluginParams->get( 'def_cat_id', '' ))
                $this->view->assign('addto_article',true);
            else
            {
                $forum_ids = $pluginParams->get( 'forum_ids', '' );
                $forum_ids = explode(",", $forum_ids);
                foreach ($forum_ids as $forum_id__)
                {
                    if ($forum_id__ == $forum_id)
                    {
                        $this->view->assign('addto_article',true);
                        break;        
                    }
                }
            }
            
        }

        $this->view->assign('access',$access);

        // create pagination with respect to current page
        $per_page = intval($this->agora_user['disp_posts']) > 0 ? $this->agora_user['disp_posts'] : intval($this->agora_config['o_disp_posts_default']);
        $num_pages = ceil(($topic['num_replies'] + 1) / $per_page);
        $this->setPagination($num_pages);
        $page = Agora::getPage($num_pages);

        if ($topic['question']) {
            $this->_processPoll($topic);
        }

        // get posts and process then
        $posts = $topic_model->loadPosts($topic_id, $per_page, $page, intval($this->agora_user['reverse_posts']), $topic['num_replies']+1);

        $parser = & $this->helper('parser');
        
        $post_helper = & $this->helper('post');
        $posts = $post_helper->processPosts($posts, $parser);

        //Subscr update
        if ($this->agora_user['id'])
        {
            $s_model = &Model::getInstance('SubscriptionModel');
            $s_model->updateSubscriberEmailed($this->agora_user['id'], $topic_id, 0, 0);
            $s_model->updateSubscriberEmailed($this->agora_user['id'], 0, $forum_id, 0);
        }
        
        // plugin?
			// trigger before display event
			JPluginHelper::importPlugin('agora');
			$dispatcher =& JDispatcher::getInstance();
			$plugin_template =  $dispatcher->trigger('onTopicDisplay', array(&$topic_id));
			$this->view->assign('plugin_template', implode("<br />\n", $plugin_template));
        
        // Google adSense handling
        $as_model = & Model::getInstance('AdSenseModel');
        $as = $as_model->load();

        if ($as['google_adsense_enabled'] && strpos($as['google_exclude_forums'], ','.$topic['forum_id']) === FALSE ) {
            $this->view->smarty->assign('show_adsense',1);
        } else {
            $this->view->smarty->assign('show_adsense',0);
        }

        $this->_setHeadTags($forum, $topic, JRequest::getInt('p', 0));
		
        // post smilies are here
        $smilies_model = & Model::getInstance('SmiliesModel');
        $smilies = $smilies_model->loadAll();
        $this->view->assign('smilies',$smilies);
        $this->view->assign('topic',$topic);
        $this->view->assign('topic_id',$topic_id);
        $this->view->assign('forum',$forum);
        $this->view->assign('posts',$posts);
        $this->view->assign('page',$page);
        $this->view->assign('post_body',$message);
        $this->view->assign('user_banned',$banned);
		//$twitter_url = Agora::getUrlContent('http://is.gd/api.php?longurl=' . Agora::getSelf()); //TODO JOPPORT УБРАТЬ КОММЕНТАРИЙ!!! закомментировал, т.к. на работе блокируется работа из-за этого
		if ($twitter_url !== false) {
			$this->view->assign('twitter_url', $twitter_url);
			$this->view->assign('show_twitter', true);
		} else {
			$this->view->assign('show_twitter', false);
		}
		
        if ('agroup' == $mode)
        $this->view->template = 'topic_agroup';
        else
        $this->view->template = 'topic';
		
    }

    function subscribe()
    {
        $topic_id = (int)Agora::getVar('id');
        $topic_model = & Model::getInstance('TopicModel');
        $topic = $topic_model->load($topic_id);
        if (!$topic) {
            Agora::show404();
            return;
        }
		$this->authenticate($topic['forum_id'], 'read');

        $subscription_model = & Model::getInstance('SubscriptionModel');
        $subscription_model->add(array('user_id'=>$this->agora_user['id'],'topic_id'=>$topic_id));

        Agora::showMessage(Agora::lang('You are now subscribed on topic') . ' ' . AString::escape($topic['subject']));
        $this->redirect('id','!action','!page');
    }
    
    function addtoarticle()
    {
        $topic_id = (int)Agora::getVar('id');
        $topic_model = & Model::getInstance('TopicModel');
        $topic = $topic_model->load($topic_id);
        if (!$topic) {
            Agora::show404();
            return;
        }
        $forum_id = $topic['forum_id'];
		// get access parameters for forum
		$access_helper = & $this->helper('access');
		$access = $access_helper->getForumAccess($forum_id);
		

        if ($this->agora_user['is_superadmin'] || $access['can_moderate'])
        {
            $db =& JFactory::getDBO();
            $alias='topic'.$topic_id;
            $db->setQuery('SELECT id FROM #__content WHERE `alias` ='.$db->Quote($alias) );
            $content_id = $db->loadResult();
            if ($content_id)
            {
                Agora::showMessage(Agora::lang('This topic is already into articles'));
                $this->redirect('id','!action','!page');
                return;
            }
            
            JPluginHelper::importPlugin( 'agora', 'agoraautoarticle');
            $plugin       =& JPluginHelper::getPlugin('agora', 'agoraautoarticle');
			$plugin_params = (is_object($plugin) && property_exists($plugin, 'params')) ? $plugin->params : null;
	        $pluginParams = new JParameter( $plugin_params );
	        
	        $db->setQuery('SELECT message FROM #__agora_posts WHERE topic_id = '.intval($topic_id).' ORDER BY posted LIMIT 1');
            $message = $db->loadResult();
            
	        if (!$pluginParams->get( 'plg_mode', '' ))
	        {
	            $dispatcher =& JDispatcher::getInstance();
                $params=array($forum_id, $topic_id, $topic['subject'], $topic['descrip_t'], $message, $topic['poster'] );
                $dispatcher->trigger( 'onAutoArticle', $params);
                Agora::showMessage(Agora::lang('You added this topic to articles'));
	        }
        }
		
        $this->redirect('id','!action','!page');
    }

	function unsubscribe() {
		$guest_email = urldecode(Agora::getVar('email'));
		$topic_id = (int)Agora::getVar('id');
		$topic_model = & Model::getInstance('TopicModel');
		$topic = $topic_model->load($topic_id);
		if (!$topic) {
			Agora::show404();
			return;
		}
		$this->authenticate($topic['forum_id'], 'read');
		
		$subscription_model = & Model::getInstance('SubscriptionModel');
		
		// if not a user, check email
		if (!$this->agora_user['id']) {
			if (empty($guest_email)) {
				Agora::showMessage(Agora::lang('Access denied'));
				Agora::redirect(Agora::getRefferer());exit;
			}
			$subscription_model->deleteByEmail($guest_email, $topic_id);
		}
		else {
			$subscription_model->delete($this->agora_user['id'], $topic_id);
		}
		Agora::showMessage(Agora::lang('You are now unsubscribed from topic') . ' ' . AString::escape($topic['subject']));
		$this->redirect('id','!action','!page');
	}

    function sticky()
    {
        $topic_id = (int)Agora::getVar('id');
		$this->authenticateTopic($topic_id, 'make_sticky');
        $topic_model = & Model::getInstance('TopicModel');
        $topic_model->edit($topic_id,array('sticky'=>1), null, null);

        Agora::showMessage(Agora::lang('Topic is sticky now'));
        $this->redirect('id','!action','!page');
    }

    function unsticky()
    {
        $topic_id = (int)Agora::getVar('id');
		$this->authenticateTopic($topic_id, 'make_sticky');
        $topic_model = & Model::getInstance('TopicModel');
        $topic_model->edit($topic_id,array('sticky'=>0), null, null);
        Agora::showMessage(Agora::lang('Topic is not sticky now'));
        $this->redirect('id','!action','!page');
    }

    function close() {
        $topic_id = (int)Agora::getVar('id');
		$this->authenticateTopic($topic_id, 'close_topic');
        $topic_model = & Model::getInstance('TopicModel');
        $topic_model->edit($topic_id,array('closed'=>1), null, null);
        Agora::showMessage(Agora::lang('Topic is closed now'));
        $this->redirect('id','!action','!page');
    }

    function open() {
        $topic_id = (int)Agora::getVar('id');
		$this->authenticateTopic($topic_id, 'close_topic');
        $topic_model = & Model::getInstance('TopicModel');
        $topic_model->edit($topic_id,array('closed'=>0), null, null);
        Agora::showMessage(Agora::lang('Topic is open now'));
        $this->redirect('id','!action','!page');
    }

    function split()
    {
        if ( strpos($_SERVER['PHP_SELF'],'index2.php')!=0 ) $mode='agroup';
        else $mode='';
        
        $source_topic = (int)Agora::getRequestVar('topic_id');
        $source_post = (int)Agora::getRequestVar('post_id');
        $dest_forum = (int)Agora::getRequestVar('id');
        $splitpost = Agora::getRequestVar('splitpost');

        if (!$dest_forum) {
            if ('agroup'==$mode)
            $this->view->assign('url', Agora::makeURL(array('task'=>'topic','action'=>'split','topic_id'=>$source_topic,'post_id'=>$source_post),true,true));
            else
            $this->view->assign('url', Agora::makeURL(array('task'=>'topic','action'=>'split','topic_id'=>$source_topic,'post_id'=>$source_post)));
            
            $topic_model = & Model::getInstance('TopicModel');
            $topic = $topic_model->load($source_topic);
            $posts = $topic_model->loadPosts($source_topic, null, null, intval($this->agora_user['reverse_posts']), $topic['num_replies']+1, $source_post);
            $parser = & $this->helper('parser');
        
            $post_helper = & $this->helper('post');
            $posts = $post_helper->processPosts($posts, $parser);
            $this->view->assign('posts',$posts);
            //print_r($posts);
            $this->view->template = 'post/select_forum';
            return;
        }
        
        $splitpost_arr=array();
        if($splitpost)
        foreach ($splitpost as $k=>$v)
        {
            $splitpost_arr[]=$k;
        }

        $this->authenticate($dest_forum,'post_topic');

        $post_model = & Model::getInstance('PostModel');
        $post = $post_model->load($source_post);
        //$post_model->delete($source_post);

        $forum_model = & Model::getInstance('ForumModel');

        $forum = $forum_model->load($dest_forum);
        $this->view->assign('forum',$forum);

        $icons_model = & Model::getInstance('TopicIconsModel');
        $this->view->assign('post_body',$post['message']);
        $this->view->assign('cur_forum_id',intval($dest_forum));
        $this->view->assign('topic_icons',$icons_model->loadAll());
        
        $this->view->assign('source_post',$source_post);
        $this->view->assign('topic_username',$post['poster']);
        $this->view->assign('topic_userid',$post['poster_id']);

        if (count($splitpost_arr))
        $this->view->assign('splitpost',$splitpost_arr);

        $this->view->template = 'post/topic';
    }

    function merge() {
        $source_topic = (int)Agora::getRequestVar('source_id');
        $dest_id = (int)Agora::getRequestVar('topic_id');
        $forum_id = (int)Agora::getRequestVar('id');

        $this->authenticateTopic($source_topic,'close_topic');
		
        if (!$forum_id) {
            $this->view->assign('url', Agora::makeURL(array('task'=>'topic','action'=>'merge','source_id'=>$source_topic,'type'=>'clean')));
            $this->view->template = 'post/select_forum_move';
            return;
        }

        if (!$dest_id) {
            $forum_model = &Model::getInstance('ForumModel');
            $forum = $forum_model->load($forum_id);
            $topics = $forum_model->loadTopics($forum_id, null, null, $forum['sort_by'] == 1 ? 'posted' : 'last_post');
            foreach ($topics as $key=>$topic) {
                if ($topic['id'] == $source_topic) {
                    unset($topics[$key]);
                    break;
                }
            }
            $this->view->assign('topics',$topics);
            $this->view->assign('url', Agora::makeURL(array('task'=>'topic','action'=>'merge','source_id'=>$source_topic,'id'=>$forum_id,'type'=>'clean')));
            $this->view->template = 'post/select_topic';
            return;
        }

        $this->authenticate($forum_id,'post_topic');

        $topic_model = &Model::getInstance('TopicModel');
        $topic_model->merge($source_topic, $dest_id);
        Agora::showMessage(Agora::lang('Topic merged'));
        $this->redirect('page=topic','id='.intval($dest_id));
    }

    function move() {
        $source_topic = (int)Agora::getRequestVar('source_id');
        $forum_id = (int)Agora::getRequestVar('id');

        $this->authenticateTopic($source_topic,'close_topic');

        if (!$forum_id) {
            $this->view->assign('url', Agora::makeURL(array('task'=>'topic','action'=>'move','source_id'=>$source_topic,'type'=>'clean')));
            $this->view->template = 'post/select_forum';
            return;
        }

        $this->authenticate($forum_id,'post_topic');

        $topic_model = &Model::getInstance('TopicModel');
        $topic_model->move($source_topic,$forum_id);

        Agora::showMessage(Agora::lang('Topic moved'));
        $this->redirect('page=topic','id='.intval($source_topic));
    }
    
    //Joopport added ДАЛЕе ВСЕ ИЗ ДЖУППОРТ хака НИЖЕ!!!!!!!!!!!!!!!!!
    
    function change_joopstatus()
    {
    	$topic_id = (int)Agora::getVar('id');
    	$topic_type = (int)Agora::getVar('type');
    	$this->authenticateTopic($topic_id, 'make_sticky');
    	$topic_model = & Model::getInstance('TopicModel');
    	$topic_model->edit($topic_id,array('joopstatus'=>$topic_type), null, null);
    
    	Agora::showMessage(Agora::lang('Topic support status changed'));
    	$this->redirect('id','!action','!page');
    }
    
}

?>
